package com.asset.service.impl;

import com.asset.web.interceptor.LoginInterceptor;
import com.asset.dto.UserDto;
import com.asset.mapper.DepaMapper;
import com.asset.mapper.UserMapper;
import com.asset.pojo.Department;
import com.asset.pojo.Role;
import com.asset.pojo.User;
import com.asset.service.RoleService;
import com.asset.service.UserService;
import com.asset.util.AssetExceptionEnum;
import com.asset.util.AssetManageException;
import com.asset.util.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户服务接口实现类
 *
 * @author 11725
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private DepaMapper depaMapper;

    @Resource
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = new User();
        user.setUsername(username);
        User userDetail = userMapper.selectOne(user);

        if (userDetail == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 获取角色信息
        List<Role> roles = roleService.selectByUserId(userDetail.getId());

        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        userDetail.setRoleList(authorities);

        return userDetail;
    }

    @Override
    public PageResult<UserDto> selectByPage(Integer page, Integer rows, String keyword, Long depaId, Long rid) {
        // 分页处理
        PageHelper.startPage(page, rows);

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        // 判断是否存在关键字
        if (!StringUtils.isBlank(keyword)) {
            // 存在，对 用户名 或 姓名 进行模糊查询
            criteria.andLike("username", "%" + keyword + "%")
                    .orLike("name", "%" + keyword + "%");
        }

        if (depaId != null) {
            criteria.andEqualTo("depaId", depaId);
        }

        // TODO - 角色过滤


        // 分页查询用户信息
        List<User> userList = userMapper.selectByExample(example);

        if (userList == null) {
            throw new RuntimeException("匹配的结果集为空！");
        }
        List<UserDto> result = packageUserDtoList(userList);

        PageInfo<User> info = new PageInfo<>(userList);

        return new PageResult<UserDto>(info.getTotal(), result);
    }

    public User login(User user) {
        User record = new User();
        record.setUsername(user.getUsername());
        record.setPassword(user.getPassword());
        List<User> result = userMapper.select(record);
        if (result.size() != 1) {
            // 用户名或密码错误
            throw new AssetManageException(AssetExceptionEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        return result.get(0);
    }

    @Override
    public UserDto selectById(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new AssetManageException(AssetExceptionEnum.USER_NOT_FOUND);
        }
        return new UserDto(user);
    }

    @Override
    public UserDto verify() {
        User user = LoginInterceptor.getUser();

        if (user != null) {
            log.info("[service:user:verify] - 用户验证：{}", user.getUsername());
            return new UserDto(user);
        }
        log.info("[service:user:verify] - 用户未登录");
        return null;
    }

    @Override
    public List<UserDto> selectByIds(List<Long> ids) {
        List<UserDto> result = new ArrayList<>();

        List<User> userList = userMapper.selectByIdList(ids);
        userList.forEach(user -> {
            UserDto userDto = new UserDto();
            userDto.setUsername(user.getUsername());
            userDto.setName(user.getName());
            userDto.setId(user.getId());

            result.add(userDto);
        });

        return result;
    }

    private List<UserDto> packageUserDtoList(List<User> userList) {
        // 获取部门信息
        Set<Long> depaSet = userList.stream().map(User::getDepaId).collect(Collectors.toSet());
        List<Department> depaList = depaMapper.selectByIdList(new ArrayList<>(depaSet));

        // TODO - 获取角色信息

        return new ArrayList<>(userList.size());
    }
}
